<template>
  <div class="capacity-analysis">
    <el-card class="header-card">
      <div class="page-header">
        <div class="header-left">
          <h2>
            <el-icon><DataAnalysis /></el-icon>
            产能分析
          </h2>
          <p>分析生产产能，优化资源配置</p>
        </div>
        <div class="header-right">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateChange"
          />
          <el-button type="primary" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出报告
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 关键指标 -->
    <div class="kpi-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="kpi-card">
            <div class="kpi-content">
              <div class="kpi-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                <el-icon><Odometer /></el-icon>
              </div>
              <div class="kpi-info">
                <div class="kpi-value">{{ kpiData.actualCapacity }}</div>
                <div class="kpi-label">实际产能（件）</div>
                <div class="kpi-trend">
                  <el-icon color="#67c23a"><CaretTop /></el-icon>
                  <span style="color: #67c23a">+12.5%</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="kpi-card">
            <div class="kpi-content">
              <div class="kpi-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="kpi-info">
                <div class="kpi-value">{{ kpiData.plannedCapacity }}</div>
                <div class="kpi-label">计划产能（件）</div>
                <div class="kpi-trend">
                  <span style="color: #909399">目标值</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="kpi-card">
            <div class="kpi-content">
              <div class="kpi-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%)">
                <el-icon><Promotion /></el-icon>
              </div>
              <div class="kpi-info">
                <div class="kpi-value">{{ kpiData.utilizationRate }}%</div>
                <div class="kpi-label">产能利用率</div>
                <div class="kpi-trend">
                  <el-icon color="#67c23a"><CaretTop /></el-icon>
                  <span style="color: #67c23a">+5.8%</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="kpi-card">
            <div class="kpi-content">
              <div class="kpi-icon" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)">
                <el-icon><DataLine /></el-icon>
              </div>
              <div class="kpi-info">
                <div class="kpi-value">{{ kpiData.efficiency }}%</div>
                <div class="kpi-label">综合效率（OEE）</div>
                <div class="kpi-trend">
                  <el-icon color="#f56c6c"><CaretBottom /></el-icon>
                  <span style="color: #f56c6c">-2.1%</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>车间产能对比</span>
              <el-radio-group v-model="workshopChartType" size="small">
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="line">折线图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="workshopChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>产能趋势分析</span>
          </template>
          <div class="chart-container" ref="trendChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>设备利用率分布</span>
          </template>
          <div class="chart-container" ref="equipmentChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span>产能瓶颈分析</span>
          </template>
          <div class="chart-container" ref="bottleneckChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="table-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>车间产能明细</span>
          <el-button size="small" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table :data="tableData" stripe border>
        <el-table-column prop="workshop" label="车间" width="150" />
        <el-table-column prop="plannedCapacity" label="计划产能" width="120" align="right" />
        <el-table-column prop="actualCapacity" label="实际产能" width="120" align="right">
          <template #default="{ row }">
            <span :style="{ color: row.actualCapacity >= row.plannedCapacity ? '#67c23a' : '#f56c6c' }">
              {{ row.actualCapacity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="utilizationRate" label="产能利用率" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.utilizationRate" :color="getProgressColor(row.utilizationRate)" />
          </template>
        </el-table-column>
        <el-table-column prop="equipmentCount" label="设备数量" width="100" align="center" />
        <el-table-column prop="workingHours" label="工作时长(h)" width="120" align="right" />
        <el-table-column prop="outputPerHour" label="小时产量" width="120" align="right" />
        <el-table-column prop="defectRate" label="不良率" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.defectRate > 2 ? 'danger' : 'success'">
              {{ row.defectRate }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="运行状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'normal' ? 'success' : 'warning'">
              {{ row.status === 'normal' ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  DataAnalysis, Download, Odometer, TrendCharts,
  Promotion, DataLine, CaretTop, CaretBottom, Refresh
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const dateRange = ref([])
const workshopChartType = ref('bar')

const kpiData = reactive({
  actualCapacity: 45680,
  plannedCapacity: 50000,
  utilizationRate: 91.4,
  efficiency: 85.6
})

const tableData = ref([
  {
    workshop: '第一车间',
    plannedCapacity: 20000,
    actualCapacity: 18500,
    utilizationRate: 92.5,
    equipmentCount: 25,
    workingHours: 168,
    outputPerHour: 110,
    defectRate: 1.5,
    status: 'normal'
  },
  {
    workshop: '第二车间',
    plannedCapacity: 18000,
    actualCapacity: 16200,
    utilizationRate: 90.0,
    equipmentCount: 20,
    workingHours: 168,
    outputPerHour: 96,
    defectRate: 2.2,
    status: 'normal'
  },
  {
    workshop: '第三车间',
    plannedCapacity: 12000,
    actualCapacity: 10980,
    utilizationRate: 91.5,
    equipmentCount: 15,
    workingHours: 168,
    outputPerHour: 65,
    defectRate: 1.8,
    status: 'normal'
  }
])

const workshopChart = ref(null)
const trendChart = ref(null)
const equipmentChart = ref(null)
const bottleneckChart = ref(null)

const initCharts = () => {
  nextTick(() => {
    // 车间产能对比图
    if (workshopChart.value) {
      const chart1 = echarts.init(workshopChart.value)
      chart1.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['计划产能', '实际产能'] },
        xAxis: { type: 'category', data: ['第一车间', '第二车间', '第三车间'] },
        yAxis: { type: 'value', name: '产能（件）' },
        series: [
          {
            name: '计划产能',
            type: workshopChartType.value,
            data: [20000, 18000, 12000],
            itemStyle: { color: '#409eff' }
          },
          {
            name: '实际产能',
            type: workshopChartType.value,
            data: [18500, 16200, 10980],
            itemStyle: { color: '#67c23a' }
          }
        ]
      })
    }

    // 产能趋势图
    if (trendChart.value) {
      const chart2 = echarts.init(trendChart.value)
      chart2.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['实际产能', '计划产能', '产能利用率'] },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
        },
        yAxis: [
          { type: 'value', name: '产能（件）' },
          { type: 'value', name: '利用率（%）', max: 100 }
        ],
        series: [
          {
            name: '实际产能',
            type: 'line',
            data: [42000, 43500, 44200, 45000, 45680, 46200, 47000],
            smooth: true,
            itemStyle: { color: '#67c23a' }
          },
          {
            name: '计划产能',
            type: 'line',
            data: [45000, 46000, 47000, 48000, 50000, 51000, 52000],
            smooth: true,
            itemStyle: { color: '#409eff' }
          },
          {
            name: '产能利用率',
            type: 'line',
            yAxisIndex: 1,
            data: [93.3, 94.6, 94.0, 93.8, 91.4, 90.6, 90.4],
            smooth: true,
            itemStyle: { color: '#e6a23c' }
          }
        ]
      })
    }

    // 设备利用率分布图
    if (equipmentChart.value) {
      const chart3 = echarts.init(equipmentChart.value)
      chart3.setOption({
        tooltip: { trigger: 'item' },
        legend: { orient: 'vertical', left: 'left' },
        series: [
          {
            name: '设备利用率',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 45, name: '高负载（>90%）' },
              { value: 30, name: '正常（70-90%）' },
              { value: 20, name: '低负载（50-70%）' },
              { value: 5, name: '空闲（<50%）' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    }

    // 产能瓶颈分析图
    if (bottleneckChart.value) {
      const chart4 = echarts.init(bottleneckChart.value)
      chart4.setOption({
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        xAxis: { type: 'value', name: '影响程度' },
        yAxis: {
          type: 'category',
          data: ['设备故障', '原料短缺', '人员不足', '工艺问题', '质量问题']
        },
        series: [
          {
            name: '影响程度',
            type: 'bar',
            data: [35, 28, 22, 18, 12],
            itemStyle: {
              color: (params) => {
                const colors = ['#f56c6c', '#e6a23c', '#409eff', '#67c23a', '#909399']
                return colors[params.dataIndex]
              }
            }
          }
        ]
      })
    }
  })
}

const getProgressColor = (percentage) => {
  if (percentage >= 90) return '#67c23a'
  if (percentage >= 70) return '#e6a23c'
  return '#f56c6c'
}

const handleDateChange = () => {
  ElMessage.info('日期范围已更新')
  // 刷新数据
}

const handleExport = () => {
  ElMessage.success('正在导出报告...')
}

const handleRefresh = () => {
  ElMessage.success('数据已刷新')
}

onMounted(() => {
  initCharts()
})
</script>

<style scoped lang="scss">
.capacity-analysis {
  padding: 20px;

  .header-card {
    margin-bottom: 20px;
    
    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        h2 {
          display: flex;
          align-items: center;
          gap: 10px;
          margin: 0 0 10px 0;
          font-size: 24px;
          color: #303133;
        }

        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }

      .header-right {
        display: flex;
        gap: 10px;
      }
    }
  }

  .kpi-cards {
    margin-bottom: 20px;

    .kpi-card {
      .kpi-content {
        display: flex;
        align-items: center;
        gap: 20px;

        .kpi-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 28px;
        }

        .kpi-info {
          flex: 1;

          .kpi-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }

          .kpi-label {
            font-size: 14px;
            color: #909399;
            margin-bottom: 5px;
          }

          .kpi-trend {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 14px;
          }
        }
      }
    }
  }

  .chart-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 300px;
    }
  }
}
</style>

